2/22/2021

R Leaflet

Before starting, let’s see a basic example first:

R Leaflet

Leaflet is one of the most popular open-source JavaScript libraries for interactive and dynamic maps, and the R package “leaflet” makes it easy to integrate and control Leaflet maps in R.


You create a Leaflet map with these basic steps:

  1. Create a map widget by calling leaflet().
  2. Add layers to the map by using layer functions (e.g. addTiles, addMarkers, addPolygons) to modify the map widget.
  3. Repeat step 2 as desired.
  4. Print the map widget to display it.

Empirical Study


We are going to construct a dynamic and interactive map to show daily new case and new death of COVID-19 in different states.


In order to build a daily updated R shiny application later, we choosed the data provided by Johns Hopkins Whiting School of Engineering, and the link is https://github.com/CSSEGISandData/COVID-19.


Besides, we also need to download a US states’ shapefile for drawing corresponding polygons from United States Census Bureau.

Data Preprocessing

After data manipulations, we get the dataset shown below:

head(final_data,n=5)
##           States new.case new.death
## 1        Alabama      857         2
## 2         Alaska        0         0
## 3 American Samoa        0         0
## 4        Arizona     1804        25
## 5       Arkansas      284         9

Then, we import the shapfile using readOGR() function in rgdal package:

states.shape<-readOGR("cb_2018_us_state_500k/cb_2018_us_state_500k.shp")

Aligning Data with Shapefile

We should align the name and order of the states in dataset with them in the shapefile.

is.element(final_data$States,states.shape$NAME)
final_data<-final_data[-c(10,14),]
final_data$States<-factor(final_data$States)
levels(final_data$States)[38]<-"Commonwealth of the Northern Mariana Islands"
levels(final_data$States)[51]<-"United States Virgin Islands"
final_data<-final_data[order(match(final_data$States,states.shape$NAME)),]
head(final_data,n=3);states.shape$NAME[1:3]
##            States new.case new.death
## 29    Mississippi      390         0
## 38 North Carolina     2541        30
## 42       Oklahoma     1036        26
## [1] Mississippi    North Carolina Oklahoma      
## 56 Levels: Alabama Alaska American Samoa Arizona Arkansas ... Wyoming

Construct the basic map

Dmap<-leaflet(height = 300, width = 750) %>% #build a leaflet objection
  addProviderTiles(provider = providers$Stamen.Toner) %>%
  setView(lng = -96,lat = 37.8,zoom = 3.5) #localize the map
Dmap

Add states’ polygons layer

#create the color pallet
bins<-c(0,10,100,500,2500,5000,10000,15000,Inf)
pal<-colorBin("RdYlBu",domain = c(0,1),bins = bins)
Dmap<-leaflet() %>% 
  addProviderTiles(provider = providers$Stamen.Toner) %>%
  setView(lng = -96,lat = 37.8,zoom = 3.5) %>%
  addPolygons(data = states.shape,
              weight = 1, #boundary thickness
              color = "white", #boundary color
              fillOpacity = 0.5, #opacity of polygons
              fillColor = pal(final_data$new.case)
              ) %>%
    addLegend(pal=pal,
            values = final_data$new.case,
            opacity = 0.7,
            position = "topright")

Add states’ polygons layer

Highlight Options

Dmap<-leaflet() %>% 
  addProviderTiles(provider = providers$Stamen.Toner) %>%
  setView(lng = -96,lat = 37.8,zoom = 3.5) %>%
  addPolygons(data = states.shape,
              weight = 1, #boundary thickness
              color = "white", #boundary color
              fillOpacity = 0.5, #opacity of polygons
              fillColor = pal(final_data$new.case),
              highlightOptions = highlightOptions(
                weight = 5,
                color = "#666666",
                fillOpacity = 0.7,
                bringToFront = TRUE
              )) %>%
    addLegend(pal=pal,
            values = final_data$new.case,
            opacity = 0.7,
            position = "topright")

Highlight Options

Add labels

case.labels<-paste("<p>",final_data$States,"</p>",
                 "<p>","Daily new case: ",final_data$new.case,"</p>",sep="")

Dmap<-leaflet() %>% 
  addProviderTiles(provider = providers$Stamen.Toner) %>%
  setView(lng = -96,lat = 37.8,zoom = 3.5) %>%
  addPolygons(data = states.shape, 
              weight = 1, 
              color = "white", 
              fillOpacity = 0.5, 
              fillColor = pal(final_data$new.case),
              label = lapply(case.labels,HTML),
              highlightOptions = highlightOptions(
                weight = 5,
                color = "#666666",
                fillOpacity = 0.7,
                bringToFront = TRUE
              )) %>%
  addLegend(pal=pal, 
            values = final_data$new.case, 
            opacity = 0.7)

Add labels

Interactive plots

Dmap<-leaflet() %>% 
  addProviderTiles(provider = providers$Stamen.Toner) %>%
  setView(lng = -96,lat = 37.8,zoom = 3.5) %>%
  addPolygons(data = states.shape, weight = 1, color = "white", fillOpacity = 0.5, 
              fillColor = pal(final_data$new.case),
              label = lapply(case.labels,HTML),
              group = "case",
              highlightOptions = highlightOptions(
                weight = 5,
                color = "#666666",
                fillOpacity = 0.7,
                bringToFront = TRUE
              )) %>%
  addPolygons(data = states.shape, weight = 1, color = "white", fillOpacity = 0.5, 
              fillColor = pal(final_data$new.death),
              label = lapply(death.labels,HTML),
              group = "death",
              highlightOptions = highlightOptions(
                weight = 5,
                color = "#666666",
                fillOpacity = 0.7,
                bringToFront = TRUE
              )) %>%
  addLayersControl(baseGroups = c("case","death"))

Interactive plots

R Shiny

Shiny is an R package that makes it easy to build interactive web apps straight from R.

There are three components:

1.A user interface object(ui):
which controls the layout and appearance of your app

2.A server function:
which contains the instructions that your computer needs to build your app

3.A statement to run the application

Demo

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    dashboardSidebar(
      #1.Add control widgets
    ),
    dashboardBody(
      #2.create a output object 
    )
)

server <- function(input, output) {
  
  #3.reactive expressions
  
  #4.R code to build your output
  
}

shinyApp(ui = ui, server = server)

Brief Explanation

Control widgets:
A web element that your users can interact with.

Create a output object:
e.g. plotOutput(“Hello”) creates a plot output named “Hello” in your user interface.

Reactive expressions:
A reactive expression saves its result the first time you run it. The next time the reactive expression is called, it checks whether the widgets it depends on have changed. If the value is out of date, the reactive object will recalculate it,and if not, return the saved value without doing any computation.

R code to build your output:
e.g. output$Hello<-renderPlot({}) will construct your plot output.

Tips


Every time users open your R shiny application, R shiny will run all code in your script. Every time users change the widgets’ values, R shiny will run the code in server function.


When name, try your best to use the easy-understanding names. This will help a lot in a large project.


Arrange and note your code properly. This helps all time.

R Tutoring

In “dplyr” package

%>%: This operator will forward a value, or the result of an expression, into the next function call/expression

select(): Select variables(by names or index) in a dataframe

group_by(): Group the dataframe by some variables

summarise(): Summarise each group to fewer rows

In “base” package:

merge(): Merge two dataframes by a same index

match(): Returns a vector of the positions of matches of its first argument in its second

lapply(): Apply a function over a vector

Conclusion